package com.wondersgroup.fjzlpt.org.controller.rest.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.util.LoggerUtil;
import com.wondersgroup.fjzlpt.org.beans.req.jkcs.*;
import com.wondersgroup.fjzlpt.org.beans.resp.BaseRespBean;
import com.wondersgroup.fjzlpt.org.beans.resp.jkcs.*;
import com.wondersgroup.fjzlpt.org.dao.inter.jtqy.QysjbDao;
import com.wondersgroup.fjzlpt.org.dao.inter.jtqy.QyxxDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.ksxx.KsxxDAO;
import com.wondersgroup.fjzlpt.org.dao.inter.yljgry.YljgryDAO;
import com.wondersgroup.fjzlpt.org.service.inter.fwb.FwbService;
import com.wondersgroup.fjzlpt.org.service.inter.fwxx.FwxxService;
import com.wondersgroup.fjzlpt.org.service.inter.jtqy.JtqyService;
import com.wondersgroup.fjzlpt.org.service.inter.tdgl.TdglService;
import com.wondersgroup.fjzlpt.org.service.inter.wdqyhz.WdqyhzService;
import com.wondersgroup.fjzlpt.org.service.inter.xymb.XymbService;
import com.wondersgroup.fjzlpt.org.service.inter.yljgxx.YljgxxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 为健康城市项目提供的接口
 * @author gzb   
 * 2017年7月20日
 */
@RestController
@RequestMapping("/jkcsApi")
@Api(value = "健康城市接口" , tags = {"健康城市预签约相关接口"} , description = "健康城市预签约相关接口")
public class JkcsApiRestController {

	@Autowired
	private TdglService tdglService;
	@Autowired
	private FwbService fwbService;
	@Autowired
	private JtqyService jtqyService;
	@Autowired
	private WdqyhzService wdqyhzService;
	@Autowired
	private YljgxxService yljgxxService;
	@Autowired
	private KsxxDAO ksxxDAO;
	@Autowired
	private YljgryDAO yljgryDAO;
	@Autowired
	private QyxxDAO qyxxDAO;
	@Autowired
	private XymbService xymbService;
	@Autowired
	private QysjbDao qysjbDao;
	@Autowired
	private FwxxService fwxxService;

	/**
	 * 分页查询团队信息到健康城市系统
	 * @param queryTdxxByPageReq {XZQHDM=xxx,YLJGDM=xxx,pageSize=xxx,pageNumber=xxx}其中：pageSize和pageNumber必传
	 * @return
	 */
	@ApiOperation(value = "分页查询团队信息" , notes = "分页查询团队信息" , response = QueryTdxxByPageResp.class)
	@RequestMapping(value="/queryTdxxByPageToJkcs", method = RequestMethod.POST)
	public JSONObject queryTdxxByPageToJkcs(@RequestBody QueryTdxxByPageReq queryTdxxByPageReq){
		JSONObject json = JSON.parseObject(JSON.toJSONString(queryTdxxByPageReq));
		LoggerUtil.info("\n健康城市api接口queryTdxxByPageToJkcs入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写
		
		JSONObject result = tdglService.queryTdxxByPageToJkcs((Map)json);
		result = jsonKeyFormat(result,"lower");
		LoggerUtil.info("健康城市api接口queryTdxxByPageToJkcs校验结果：\n" + result.toJSONString());
		return result;
	}

	/**
	 * 查询团队成员信息到健康城市系统
	 * @param queryTdcyListReq {TDID=xxx}
	 * @return
	 */
	@ApiOperation(value = "查询团队成员信息" , notes = "查询团队成员信息" , response = QueryTdcyListResp.class,responseContainer = "List")
	@RequestMapping(value="/queryTdcyListToJkcs", method = RequestMethod.POST)
	public JSONArray queryTdcyListToJkcs(@RequestBody QueryTdcyListReq queryTdcyListReq){
		JSONObject json = JSON.parseObject(JSON.toJSONString(queryTdcyListReq));
		LoggerUtil.info("\n健康城市api接口queryTdcyListToJkcs入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写

		JSONArray result = tdglService.queryTdcylbAll((Map)json);
		result = this.jsonAryKeyLower(result);
		LoggerUtil.info("健康城市api接口queryTdcyListToJkcs校验结果：\n" + result.toJSONString());
		return result;
	}
	
	/**
	 * 查询服务包基本信息和服务包服务列表信息到健康城市系统
	 * @param queryFwbAndFwxxListReq {JGXZQHDM=xxx,YLJGID=xxx}
	 * @return
	 */
	@ApiOperation(value = "查询服务包基本信息和服务包服务列表" , notes = "查询服务包基本信息和服务包服务列表" , response = QueryFwbAndFwxxListResp.class,responseContainer = "List")
	@RequestMapping(value="/queryFwbAndFwxxListToJkcs", method = RequestMethod.POST)
	public JSONArray queryFwbAndFwxxListToJkcs(@RequestBody QueryFwbAndFwxxListReq queryFwbAndFwxxListReq){
		JSONObject json = JSON.parseObject(JSON.toJSONString(queryFwbAndFwxxListReq));
		LoggerUtil.info("\n健康城市api接口queryFwbAndFwxxListToJkcs入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写
		json.put("FWBZT", "1");// 服务包状态

		JSONArray result = fwbService.queryFwbAndFwxxListToJkcs((Map)json);
		result = jsonAryKeyLower(result);
		LoggerUtil.info("健康城市api接口queryFwbAndFwxxListToJkcs校验结果：\n" + result.toJSONString());
		return result;
	}
	
	/**
	 * 保存健康城市系统预签约数据
	 * @param addQyReq
	 * @return
	 */
	@ApiOperation(value = "保存预签约数据" , notes = "保存预签约数据" , response = BaseRespBean.class)
	@RequestMapping(value="/addYqyToJkcs", method = RequestMethod.POST)
	public JSONObject addYqyToJkcs(@RequestBody()AddQyReq addQyReq) {
		//如果证件类型没传，默认给01 身份证类型！
		if(StringUtils.isEmpty(addQyReq.getJmxx().getZjlx())){
			addQyReq.getJmxx().setZjlx("01");
		}
		JSONObject json = JSON.parseObject(JSON.toJSONString(addQyReq));
		LoggerUtil.info("\n健康城市api接口addYqyToJkcs入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写
		json.put("JMXX",json.getJSONObject("JMXX").toJSONString());
		json.put("QYXX",json.getJSONObject("QYXX").toJSONString());

		JSONObject result = jtqyService.addYqyToJkcs((Map)json);
		result = jsonKeyFormat(result,"lower");
		LoggerUtil.info("健康城市api接口addYqyToJkcs校验结果：\n" + result.toJSONString());
		return result;
	}
	
	/**
	 * 查询签约历史记录到健康城市系统
	 * @param queryQyHistoryByPageReq {ZJHM=xxx}
	 * @return
	 */
	@ApiOperation(value = "查询签约历史记录" , notes = "查询签约历史记录" , response = QueryQyHistoryResp.class)
	@RequestMapping(value="/queryQyHistoryToJkcs", method = RequestMethod.POST)
	public JSONObject queryQyHistoryByPageToJkcs(@RequestBody QueryQyHistoryByPageReq queryQyHistoryByPageReq) {
		JSONObject json = JSON.parseObject(JSON.toJSONString(queryQyHistoryByPageReq));
		LoggerUtil.info("\n健康城市api接口queryQyHistoryToJkcs入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写

		JSONObject result = jtqyService.queryQyHistoryByPageToJkcs((Map)json);
		result = jsonKeyFormat(result,"lower");
		LoggerUtil.info("健康城市api接口queryQyHistoryToJkcs校验结果：\n" + result.toJSONString());
		return result;
	}
	
	
	/**
	 * 分页查询签约服务列表到健康城市系统
	 * @param queryQyfwByPageReq
	 * @return
	 */
	@ApiOperation(value = "查询签约服务列表" , notes = "分页查询签约服务列表" , response = QueryQyfwByPageResp.class)
	@RequestMapping(value="/queryQyfwByPageToJkcs", method = RequestMethod.POST)
	public JSONObject queryQyfwByPageToJkcs(@RequestBody() QueryQyfwByPageReq queryQyfwByPageReq){
		JSONObject json = JSON.parseObject(JSON.toJSONString(queryQyfwByPageReq));
		LoggerUtil.info("\n健康城市api接口queryQyfwByPageToJkcs入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写

		JSONObject result = wdqyhzService.queryQyfwByPageToJkcs((Map)json);
		result = jsonKeyFormat(result,"lower");
		LoggerUtil.info("健康城市api接口queryQyfwByPageToJkcs校验结果：\n" + result.toJSONString());
		return result;
	}
	
	/**
	 * 查询已完成服务列表到健康城市
	 * @param queryYwcfwByPageReq {QYXXID=xxx,FWBID=xxx,FWID=xxx}
	 * @return
	 */
	@ApiOperation(value = "查询已完成服务列表" , notes = "查询已完成服务列表" , response = QueryYwcfwByPageResp.class)
	@RequestMapping(value="/queryYwcfwByPageToJkcs", method = RequestMethod.POST)
	public JSONObject queryYwcfwByPageToJkcs(@RequestBody() QueryYwcfwByPageReq queryYwcfwByPageReq){
		JSONObject json = JSON.parseObject(JSON.toJSONString(queryYwcfwByPageReq));
		LoggerUtil.info("\n健康城市api接口queryYwcfwByPageToJkcs入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写
		json.put("FWZT", "1");// 服务状态：已完成

		JSONObject result = wdqyhzService.queryYwcfwByPageToJkcs((Map)json);
		result = jsonKeyFormat(result,"lower");
		LoggerUtil.info("健康城市api接口queryYwcfwByPageToJkcs校验结果：\n" + result.toJSONString());
		return result;
	}
	
	
	/**
	 * 查询所有医疗机构信息
	 * @param map 
	 * @return
	 */
	@ApiIgnore
	@RequestMapping(value="/queryYljgxxAll", method = RequestMethod.POST)
	public JSONArray queryYljgxxAll(@RequestBody() Map<String, String> map){
		return yljgxxService.queryAll(map);
	}
	
	/**
	 * 查询所有科室信息
	 * @param map 
	 * @return
	 */
	@ApiIgnore
	@RequestMapping(value="/queryKsxxAll", method = RequestMethod.POST)
	public JSONArray queryKsxxAll(@RequestBody(required = false) Map<String, String> map){
		return ksxxDAO.queryAll(map);
	}
	
	/**
	 * 查询所有医疗机构人员
	 * @param map 
	 * @return
	 */
	@ApiIgnore
	@RequestMapping(value="/queryYljgryAll", method = RequestMethod.POST)
	public JSONArray queryYljgryAll(@RequestBody(required = false) Map<String, String> map){
		return yljgryDAO.queryAll(map);
	}
	
	/**
	 * 分页查询某个医生所在团队的居民信息列表
	 * @param queryJmxxByPageReq {USERID=xxx,QYLX=xxx,pageSize=xxx,pageNumber=xxx} 注： USERID:医生id,QYLX:签约类型
	 * @return
	 */
	@ApiOperation(value = "团队的居民信息列表" , notes = "分页查询某个医生所在团队的居民信息列表" , response = QueryJmxxByPageResp.class)
	@RequestMapping(value="/queryJmxxByPage", method = RequestMethod.POST)
	public JSONObject queryJmxxByPage(@RequestBody QueryJmxxByPageReq queryJmxxByPageReq){
		JSONObject json = JSON.parseObject(JSON.toJSONString(queryJmxxByPageReq));
		LoggerUtil.info("\n健康城市api接口queryJmxxByPage入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写

		JSONObject result = qyxxDAO.queryPageForGzt((Map)json);
		result = jsonKeyFormat(result,"lower");
		LoggerUtil.info("健康城市api接口queryJmxxByPage校验结果：\n" + result.toJSONString());
		return result;
	}
	
	/**
	 * 判断居民是否已经存在签约信息(包括预签约)
	 * @param isExistReq {ZJHM=xxx}
	 * @return
	 */
	@ApiOperation(value = "签约判断" , notes = "判断居民是否已经存在签约信息(包括预签约)" , response = BaseRespBean.class)
	@RequestMapping(value="/isExist", method = RequestMethod.POST)
	public JSONObject isExist(@RequestBody() IsExistReq isExistReq){
		JSONObject json = JSON.parseObject(JSON.toJSONString(isExistReq));
		LoggerUtil.info("\n健康城市api接口isExist入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写

		JSONObject result = jtqyService.isExist((Map)json);
		result = jsonKeyFormat(result,"lower");
		LoggerUtil.info("健康城市api接口isExist校验结果：\n" + result.toJSONString());
		return result;
	}

	/**
	 * 审核预签约记录（同意签约/拒绝签约）
	 * @param checkYqyDataReq {QYXXID=xxx,type=xxx}  注：type='agree' || type='noagree'
	 * @return
	 */
	@ApiOperation(value = "审核预签约记录" , notes = "审核预签约记录" , response = BaseRespBean.class)
	@RequestMapping(value="/checkYqyData", method = RequestMethod.POST)
	public JSONObject checkYqyData(@RequestBody() CheckYqyDataReq checkYqyDataReq){
		JSONObject json = JSON.parseObject(JSON.toJSONString(checkYqyDataReq));
		LoggerUtil.info("\n健康城市api接口checkYqyData入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写
		json.put("type",json.remove("TYPE"));

		JSONObject result = jtqyService.checkYqyData((Map)json);
		result = jsonKeyFormat(result,"lower");
		LoggerUtil.info("健康城市api接口checkYqyData校验结果：\n" + result.toJSONString());
		return result;
	}

	/**
	 * 完成服务
	 * @param finishTaskReq {FPFWID:"xxx","SJFWSJ":"xxx","BZ":"xxx",USERID:"xxx"}
	 * @return
	 */
	@ApiOperation(value = "完成服务" , notes = "完成服务" , response = FinishTaskResp.class)
	@RequestMapping(value="/finishTask", method = RequestMethod.POST)
	public JSONObject finishTask(@RequestBody() FinishTaskReq finishTaskReq){
		JSONObject json = JSON.parseObject(JSON.toJSONString(finishTaskReq));
		LoggerUtil.info("\n健康城市api接口finishTask入参如下：\n" + json.toJSONString());
		Map map = this.jsonKeyFormat(json,"upper");//key转大写

		JSONArray fpfwArr = new JSONArray();
		map.put("FWZT","1");//状态完成
		fpfwArr.add(map);

		//封装数据： {fpfwArr:[{FPFWID:"xxx","SJFWSJ":"xxx","BZ":"xxx","ZT":"1"}],USERID:"xxx"}
		Map insertMap = new HashMap();
		insertMap.put("type","update");
		insertMap.put("USERID", map.get("USERID")); //完成任务的用户
		insertMap.put("fpfwArr", fpfwArr.toString());

		JSONObject result = wdqyhzService.save(insertMap);
		result = jsonKeyFormat(result,"lower");
		LoggerUtil.info("健康城市api接口finishTask校验结果：\n" + result.toJSONString());
		return result;
	}
	/**
	 * 查询家庭签约协议模板
	 * @param queryJtqyXymbReq
	 * @return
	 */
	@ApiOperation(value = "查询家庭签约协议模板" , notes = "查询家庭签约协议模板" , response = QueryJtqyXymbResp.class)
	@RequestMapping(value="/queryJtqyXymb", method = RequestMethod.POST)
	public JSONObject queryJtqyXymb(@RequestBody() QueryJtqyXymbReq queryJtqyXymbReq){
		JSONObject result = null;
		JSONObject json = JSON.parseObject(JSON.toJSONString(queryJtqyXymbReq));
		LoggerUtil.info("\n健康城市api接口queryJtqyXymb入参如下：\n" + json.toJSONString());
		Map<String,String> map = (Map)this.jsonKeyFormat(json,"upper");//key转大写

		String action = map.get("ACTION");
		if("XYMB".equals(action)){
			//获取空白协议
			result = this.getXymb(map.get("QYXYMBID"));
		}else if("QYXYNR".equals(action)){
			//获取 空白协议 + 预签约数据
			map.put("QYXXIDS" , map.get("QYXXID"));
			result = qyxxDAO.queryAllOnView(map).getJSONObject(0);
			String XYH = qysjbDao.queryMaxXyh(result.getString("XZQHDM"));
			result.put("XYH" , XYH);
			JSONObject xymb = this.getXymb(map.get("QYXYMBID"));

			result.put("XYMB" , xymb);
		}else{
			//获取最近协议
			map.put("SJLX" , "01");
			result = jtqyService.queryQyxyToJkcs(map);
		}

		result = jsonKeyFormat(result,"lower");
		LoggerUtil.info("健康城市api接口queryJtqyXymb校验结果：\n" + result.toJSONString());
		return result;
	}

	/**
	 * 根据XYMBID参数获取协议
	 * @param XYMBID
	 * @return
	 */
	private JSONObject getXymb(String XYMBID){
		if(StringUtils.isEmpty(XYMBID)){
			return xymbService.getJtqyXymb(); //获取正在启用
		}else{
			return xymbService.queryXymb(XYMBID); //获取指定的--德清(一个医院一个协议)
		}
	}

	/**
	 * 健康城市App更新签约信息与协议
	 * @param submitQyrqToJkcsReq 签约协议相关数据
	 * @return
	 */
	@ApiOperation(value = "更新签约信息与协议" , notes = "更新签约信息与协议" , response = BaseRespBean.class)
	@RequestMapping(value="/submitQyqrToJkcs", method = RequestMethod.POST)
	public JSONObject submitQyqrToJkcs(@RequestBody() SubmitQyrqToJkcsReq submitQyrqToJkcsReq){
		JSONObject json = JSON.parseObject(JSON.toJSONString(submitQyrqToJkcsReq));
		LoggerUtil.info("\n健康城市api接口submitQyqrToJkcs入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写

		JSONObject result = jtqyService.zsQyxxUpdateForJkcs((Map)json);
		result = jsonKeyFormat(result,"lower");
		LoggerUtil.info("健康城市api接口submitQyqrToJkcs校验结果：\n" + result.toJSONString());
		return result;
	}

	/**
	 * 根据医生ID查询该医生签约的患者总数
	 * @param queryQyzsToJkcsReq {USERID=xxx}
	 * @return
	 */
	@ApiOperation(value = "根据医生ID查询该医生签约的患者总数" , notes = "根据医生ID查询该医生签约的患者总数" , response = QueryQyzsResp.class)
	@RequestMapping(value="/queryQyzsToJkcs", method = RequestMethod.POST)
	public JSONObject queryQyzsToJkcs(@RequestBody() QueryQyzsToJkcsReq queryQyzsToJkcsReq){
		JSONObject json = JSON.parseObject(JSON.toJSONString(queryQyzsToJkcsReq));
		LoggerUtil.info("\n健康城市api接口queryQyzsToJkcs入参如下：\n" + json.toJSONString());
		json = this.jsonKeyFormat(json,"upper");//key转大写
		JSONObject result = new JSONObject();
		result.put("qyzs",jtqyService.queryQyzsToJkcs((Map)json));

		LoggerUtil.info("健康城市api接口queryQyzsToJkcs校验结果：\n" + result.toJSONString());
		return result;
	}

	/**
	 * 查询医保服务项列表
	 * 	注:居民选择的服务包包含医保服务包时调用该接口查询列表进行医保服务项的搭配
	 * @param queryQyzsToJkcsReq
	 * @return
	 */
	@ApiOperation(value = "查询医保服务项列表" , notes = "查询医保服务项列表" , response = QueryYbfwxToJkcsResp.class)
	@RequestMapping(value="/queryYbfwxToJkcs", method = RequestMethod.POST)
	public JSONObject queryYbfwxToJkcs(@RequestBody() QueryYbfwxToJkcsReq queryQyzsToJkcsReq){
		JSONObject result = new JSONObject();
		JSONObject json = JSON.parseObject(JSON.toJSONString(queryQyzsToJkcsReq));
		LoggerUtil.info("\n健康城市api接口queryYbfwxToJkcs入参如下：\n" + json.toJSONString());
		if(StringUtils.isEmpty(json.getString("yljgid"))){
			result.put("info","机构ID不能为空");
			result.put("state", false);
		}else{
			json = this.jsonKeyFormat(json,"upper");//key转大写
			json.put("orderByXssx","true");
			json.put("FWLB","04");
			json.put("FWZT","1");
			JSONArray fwxxAry = fwxxService.queryAll((Map)json);
			result.put("rows", fwxxAry);
			result.put("state", true);
		}

		LoggerUtil.info("健康城市api接口queryYbfwxToJkcs校验结果：\n" + result.toJSONString());
		return result;
	}

	/**
	 * 深层json对象的key值转大写/小写
	 * @param jsonObj
	 * @param type 大写:upper/小写:lower
	 */
	private static JSONObject jsonKeyFormat(JSONObject jsonObj, String type){
		Set<String> set = jsonObj.keySet();
		JSONObject newJson = new JSONObject();
		for(String key : set){
			try{
				if("pageSize".equals(key) || "pageNumber".equals(key)){
					newJson.put(key, jsonObj.getString(key));
				}else{
					JSONObject sonObj = JSONObject.parseObject(jsonObj.getString(key));
					JSONObject sonObj_= jsonKeyFormat(sonObj,type);
					newJson.put("lower".equals(type)?key.toLowerCase():key.toUpperCase(), sonObj_);
				}
			}catch (Exception e){
				try{
					JSONArray sonAry = JSONArray.parseArray(jsonObj.getString(key));
					JSONArray sonAry_= new JSONArray();
					for(int i=0;i<sonAry.size();i++){
						JSONObject item = sonAry.getJSONObject(i);
						item = jsonKeyFormat(item,type);
						sonAry_.add(item);
					}
					newJson.put("lower".equals(type)?key.toLowerCase():key.toUpperCase(), sonAry_);
				}catch (Exception e1){
					newJson.put("lower".equals(type)?key.toLowerCase():key.toUpperCase(), jsonObj.getString(key));
				}
			}
		}
		return newJson;
	}

	/**
	 * json数组的key值转小写
	 * @param jsonary
	 */
	private static JSONArray jsonAryKeyLower(JSONArray jsonary){
		JSONArray result = new JSONArray();
		for(int i=0;i<jsonary.size();i++){
			JSONObject item = jsonary.getJSONObject(i);
			item = jsonKeyFormat(item,"lower");
			result.add(item);
		}
		return result;
	}
}

